<?php
/*
 * kernel/object.api.php
 *
 * This code is distributed and used under the GNU GPL v2 License,
 * please, read file LICENSE, which is situated in root directory,
 * or in "LICENSE" directory with most acceptable translation for you
 *
 * Provides simple, but powerfull API
 *
 * Copyright (C) 2010, Taras Kudla
 *
 */

class gApi extends gKernel{

    /**
     *
     * @var <type>
     */
    private $ResponseType="json";

    /**
     * 
     */
    public function init(){
        # checking for type of response
        if( isset($_GET["response"])){
	    $response = $_GET["response"];
	    if( $response=="xml" || $response=="text" || $response=="json"){
	        $this->ResponseType=$response;
	    }
	}
    }

    /**
     * Listens to request
     *
     * @return mixed
     */
    public function listen(){
	# preparing
	$method = $_SERVER["REQUEST_METHOD"];
	$this->core->session;
	$this->core->user;
	# checking for call
	if( isset($_GET["call"]) && !empty($_GET["call"])){
	    $response = array();
	    if( preg_match("/^([A-z0-9_]{1,30})-([A-z0-9_]{1,30})$/i",$_GET["call"],$tmp)){
		$mod = $tmp[1];
		$action = $tmp[2];
		$this->core->setstate("exceptiononerror",true);
		try {
		    $data = $this->core->base->callaction($mod,$action);
		} catch ( GepardException $e){
		    $this->response(array("error"=>$e->getMessage()));
		    return false;
		}
		$this->core->restorestate("exceptiononerror");
		$this->response(array("response"=>$data,"time"=>$this->core->runtimepoint()));
		return true;
	    } else {
		$this->response(array("error"=>"Request format is incorrect"));
		return false;
	    }
	
	}
	# action call handler
	if(isset($_GET["action"]) && !empty($_GET["action"])){
		if( preg_match("/^([A-z0-9_]{1,30})-([A-z0-9_]{1,30})$/i",$_GET["action"],$tmp)){
			$hash=$this->core->base->GetHash($tmp[1],$tmp[2]);
		}else if( preg_match("/^([A-z0-9_]{"._HASH_LENGTH."})$/i",$_GET["action"],$tmp) ){
			$hash=$tmp[0];
		} else {
		    $this->response(array("error"=>"Request format is incorrect"));
		    return false;
		}
		$this->core->base->OutputKeys();
		$calls = $this->core->base->actionsbycall($tmp[1],$tmp[2]);
		$this->core->setstate("exceptiononerror",true);
		try {
		    foreach( $calls as $k=>$v){
			$this->core->base->LoadFunction($v);
		    }
		} catch( GepardException $e){
		    $this->response(array("error"=>$e->getMessage()));
		    return false;
		}
		$this->core->restorestate("exceptiononerror");

		return $this->actionresponse();
	}
	return true;
    }


    /**
     * Smart HTTP redirection
     *
     * @param string $link      ready link to follow
     */
    public function callredirect($link){
	$this->response(array("redirect"=>$link));
    }
    /**
     * Alias to callredirect()
     *
     * @param string $link
     */
    public function redirect($link){
	$this->callredirect($link);
    }

    /**
     * 
     *
     * @return <type> 
     */
    public function actionresponse(){
	$result = array();
	$outvalues = & $this->core->base->getoutvalues();
	$outdata  = & $this->core->base->getoutdata();
	foreach($outvalues as $k=>&$v){
		if(empty($v))continue;
		$result[$k]=array();
		asort($v,SORT_NUMERIC);
		foreach ($v as $a=>$b){
			$result[$k]["item"]["action"]=$a;
			$result[$k]["item"]["weight"]=$b;
			$result[$k]["item"]["content"]=$outdata[$a]["data"];
		}
	}
	$result["time"]=$this->core->runtimepoint();
	$this->response($result);
	return true;
    }


    /**
     * Creates response from data according to response type
     *
     * @param array $data
     */
    public function response($data){
	switch( $this->ResponseType){
	    case "json":
	        header("Content-type:application/json");
	        print json_encode($data);
	    break;
	    case "xml":
	        header("Content-type:text/xml");
	        print $this->core->tools->arraytoxml($data,"root");
	    break;
	    case "text":
	        header("Content-type:text/plain");
	        if( is_array($data)){
		    if( isset($data["response"]))
		        print $data["response"];
		    else if( isset($data["error"]))
		        print "error: ".$data["error"];
		    else if( isset($data["redirect"]))
		        print "redirect: ".$data["redirect"];
		    else
		        print "error: response type 'text' in not correct for your query";
		} else {
		    print $data;
		}
	    break;
	}

    }
}